package com.cqeec.myblog.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cqeec.myblog.model.Article;
import com.cqeec.myblog.model.Blogger;
import com.cqeec.myblog.model.DataDictionary;
import com.cqeec.myblog.service.ArticleService;
import com.cqeec.myblog.service.ArticleServiceImpl;

@WebServlet("/article/management.html")
public class ArticleManagementServlet extends HttpServlet {
	private static final long serialVersionUID = -5284514785181075506L;
	private ArticleService articleService = new ArticleServiceImpl();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");

		String method = request.getParameter("m");

		if ("create".equals(method)) {
			// 创建文章（跳转到文章创建页面create.jsp）
			// 获取文章分类数据
			try {
				List<DataDictionary> atList = articleService.getArticleType();
				request.setAttribute("atList", atList);
			} catch (Exception e) {
				e.printStackTrace();
			}
			request.getRequestDispatcher("../create.jsp").forward(request, response);
		} else if ("save".equals(method)) {
			// 保存文章
			String type = request.getParameter("type");
			String title = request.getParameter("title");
			String content = request.getParameter("content");
			Blogger blogger = (Blogger) request.getSession().getAttribute("blogger"); //
			Article article = new Article();
			if (blogger != null)
				article.setBlogger(blogger.getId());
			article.setType(type);
			article.setTitle(title);
			article.setContent(content);
			// 将数据保存到数据库
			try {
				articleService.saveArticle(article);

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
